package com.dqp.cslggroup.School;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.ListView;

import androidx.appcompat.widget.Toolbar;

import com.dqp.cslggroup.ConnectSever.Accept;
import com.dqp.cslggroup.ConnectSever.Send;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.UI.CollegeAdapter;
import com.dqp.cslggroup.Util.NetCheckUtil;
import com.dqp.cslggroup.Util.ToastUtil;
import com.dqp.cslggroup.bean.Club;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Objects;

public class College extends BaseActivity implements AbsListView.OnScrollListener{
    private ListView listView;
    private Handler handler;
    private ArrayList<Club> dataList;
    private LinearLayout head;
    private int count=1;
    public View loadmoreView;
    public LayoutInflater inflater;
    public int last_index;
    public int first_index;
    public int total_index;
    public boolean isLoading = false,showMore=true;//表示是否正处于加载状态
    private CollegeAdapter examAdapter;

    @SuppressLint("InflateParams")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.college);
        EventBus.getDefault().register(this);
        Toolbar toolbar = findViewById(R.id.include_toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        inflater = LayoutInflater.from(this);
        loadmoreView = inflater.inflate(R.layout.bottom, null);//获得刷新视图
        loadmoreView.setVisibility(View.GONE);//设置刷新视图默认情况下是不可见的
        listView = findViewById(R.id.college_list);
        listView.setOnScrollListener(this);
        listView.addFooterView(loadmoreView,null,false);

        head=findViewById(R.id.list_head);
        if (NetCheckUtil.checkNet(College.this)) {
            initList();
        }else {
            ToastUtil.showToast("请连接网络！");
            head.setVisibility(View.GONE);
        }
    }

    @SuppressLint({"SetTextI18n", "HandlerLeak"})
    private void initList() {
        new Thread(() -> {
            ArrayList<Club> dataList = Accept.getCollege(count);
            EventBus.getDefault().post(new MessageEvent("College", 1, dataList));
        }).start();
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        last_index = firstVisibleItem+visibleItemCount;
        first_index= firstVisibleItem;
        total_index = totalItemCount;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if(last_index == total_index && (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE)) //表示此时需要显示刷新视图界面进行新数据的加载(要等滑动停止)
        {
            if(!isLoading && showMore)
            {
                isLoading = true;  //不处于加载状态的话对其进行加载
                loadmoreView.setVisibility(View.VISIBLE);    //设置刷新界面可见
                onLoad();
            }
        }
    }

    /**
     * 刷新加载
     */
    public void onLoad()
    {
        // 加载完毕
        count++;
        new Thread(() -> {
            ArrayList<Club> addDataList = Accept.getCollege(count);
            if (addDataList.size()==0) {
                showMore = false;
            }else dataList.addAll(addDataList);
            EventBus.getDefault().post(new MessageEvent("College", 2, null));
        }).start();
    }

    /**
     * 加载完成
     */
    public void loadComplete()
    {

        loadmoreView.setVisibility(View.GONE);//设置刷新界面不可见
        isLoading = false;//设置正在刷新标志位false
        College.this.invalidateOptionsMenu();
        listView.removeFooterView(loadmoreView);//如果是最后一页的话，则将其从ListView中移出
    }

    /**
     * 加载结束
     */
    public void showBottom_line()
    {
        if (!showMore){
            @SuppressLint("InflateParams") View bottom_line = inflater.inflate(R.layout.bottom_line, null);//获得刷新视图
            bottom_line.setVisibility(View.VISIBLE);//设置刷新视图默认情况下是不可见的
            listView.addFooterView(bottom_line);
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("College")) {
            switch (event.getWhat()) {
                case 1:
                    dataList = (ArrayList<Club>) event.getObj();
                    examAdapter = new CollegeAdapter(dataList, College.this);
                    listView.setAdapter(examAdapter);
                    listView.setOnItemClickListener((adapterView, view, i, l) -> {
                        Club club=dataList.get(i);
                        String [] strings=new String[]{club.getClub_name(),"专业："+club.getClub_fine(),club.getClub_des(),club.getClub_img(),club.getClub_level()};
                        int[] ints=new int[]{club.getClub_fine(),club.getClub_bad(),club.getClub_comment()};
                        String[] show=new String[]{club.getShow1(),club.getShow2(),club.getShow3()};
                        new Thread(()-> Send.collegePv(club.getClub_name())).start();
                        Intent intent = new Intent(College.this, Club_more.class);
                        intent.putExtra("string",strings);
                        intent.putExtra("int",ints);
                        intent.putExtra("show",show);
                        intent.putExtra("view",true);
                        startActivity(intent);
                    });
                    head.setVisibility(View.GONE);
                    break;
                case 2:
                    if (showMore) examAdapter.notifyDataSetChanged();
                    loadComplete();//刷新结束
                    showBottom_line();
                    break;
            }
        }
    }
}
